<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col v-if="userRole != 3">
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="name">
              <el-input v-model="filters.name" placeholder="用户名" clearable></el-input>
            </el-form-item>
            <el-form-item prop="streetIds">
              <Region :streetValues="filters.streetIds" @regionChange="handleItemChange" :isChangeOnSelect="true">
              </Region>
            </el-form-item>
            <el-form-item prop="address">
              <el-input v-model="filters.address" placeholder="请输入地址名称"></el-input>
            </el-form-item>
            <el-form-item prop="villageId">
              <el-select placeholder="请选择小区" v-model="filters.villageId" filterable clearable>
                <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
              <!-- <el-input v-model="filters.villageName" placeholder="请输入小区名称"></el-input> -->
            </el-form-item>
            <el-form-item prop="residentAddress">
              <el-cascader placeholder="请选择XX栋XX单元XX层" :options="residentAddressList" v-model="filters.residentAddress"
                filterable clearable :props="{ label: 'name', value: 'id', checkStrictly: true }"></el-cascader>
            </el-form-item>
            <el-form-item prop="businessId">
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip class="refrush" content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <div class="table-wrapper" element-loading-text="数据加载中，请稍后..." v-loading="loading"
        :style="{ height: this.maxHeight }">
        <div class="list-item" v-for="(item, index) in dataList" @click="handleClickDetail(item)" :key="item.id">
          <div class="list-item__header">
            <el-image style="width: 111px;height:114px" fit="cover" :src="item.avatar"></el-image>
            <div class="base-info">
              <div class="name">
                {{ item.name }}
              </div>
              <div class="sex">
                {{ item.sex == 1 ? "男" : "女" }}
                <img :src="item.sex == 1
                    ? '../../../src/assets/img/male.png'
                    : '../../../src/assets/img/female.png'
                  " width="15px" alt="" />
              </div>
              <div class="age">{{ item.age }}岁</div>
            </div>
            <div class="num">序号：{{ index + 1 }}</div>
          </div>
          <div class="list-item__middle">
            <div>
              <span class="label">健康信息：</span>
              <span class="value">{{ item.healthOverview }} </span>
            </div>
            <div>
              <span class="label">最近购买：</span>
              <span class="value">{{ item.latestServerName }}</span>
            </div>
          </div>

          <el-carousel class="list-item__equip" height="155px" :autoplay="false" :loop="false" indicator-position="none">
            <el-carousel-item v-for="(item2, index) in item.equipList" :key="index">
              <div class="equip-list" @click.stop="">
                <div class="equip-item__wrapper" v-for="item3 in item2" :key="item3.id">
                  <div class="equip-item" :style="{ 'background-color': getEquipStateSytle(item3) }"
                    @click="handleEquipDetail(item3)">
                    <el-image :src="getImage(item3.type)" style="width: 100px;height: 100px;" fit="contain"></el-image>
                    <div class="equip-name line-ellipsis">
                      {{ item3.name }}
                    </div>
                    <div class="equip-other">
                      <span v-if="item3.errorState" style="color:white">
                        报警
                      </span>
                      <span v-if="item3.state == 2" style="color:white">
                        在线
                      </span>
                      <span v-else>
                        离线
                      </span>
                      |
                      <span>{{ item3.installArea }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
        <!-- <div class="empty" v-show="dataList.length == 0">
            对不起，没有找到相关数据！
          </div> -->
      </div>
      <!-- 分页工具条 -->
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page.pageNo" :page-sizes="[50, 150, 400]" :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev" :total="page.pageTotal"></el-pagination>
    </el-row>
  </div>
</template>

<script>
import { throttle } from "lodash-es";
import ResidentCardApi from "@/api/resident/residentCard";
import VillageAreaApi from "../../api/address/villageArea";
import VillageAPi from "@/api/address/village"
import Region from "@/components/Region";
export default {
  name: "ResidentCardManagement",
  inject: ["reload"], //注入局部刷新
  data() {
    return {
      userRole: "",
      page: {
        pageNo: 1,
        pageSize: 50,
        pageTotal: 0,
        totalPage: 0
      },
      filters: {
        name: "",
        address: "",
        villageName: "",
        streetIds: [],
        residentAddress: [],
        villageId: "",
        provinceId: "",
        cityId: "",
        areaId: "",
        streetId: ""
      },
      residentAddressList: [],
      villageList: [],
      maxHeight: "",
      loading: false,
      villageList: [],
      dataList: []
    };
  },
  watch: {
    "filters.streetIds"(val) {
      console.log("改变", val)
      this.villageId = "";
      this.villageName = "";
      this.villageList = [];
      if (val.length > 0) {
        this.getVillageList();
      }
    },
    "filters.villageId"(val) {
      this.residentAddress = [];
      if (val) this.getResidentAddressList();
    }
  },
  computed: {
    //   urlList() {
    //     return this.filters.type == 1 ? this.dataList.map(item => item.url) : [];
    //   }
  },
  components: {
    Region
  },
  mounted() {
    this.userRole = this.$store.getters.userRole;
    this.getTableHeight();
    this.listData();
    //   this.getBusinessList();
  },

  // handleResidentAddressChange(e){
  //     const {filters} = this
  //     filters.buildId = e[0]||""
  //     filters.unitId = e[1]||""
  //     filters.floorId = e[2]||""
  //   },
  methods: {
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight =
          window.innerHeight - this.$refs.tableRow.$el.offsetTop - 76 + "px";
        window.onresize = () => {
          this.maxHeight =
            window.innerHeight - this.$refs.tableRow.$el.offsetTop - 76 + "px";
        };
      });
    },
    getEquipStateSytle({ state, errorState }) {
      if (errorState) {
        return "rgba(245, 114, 114, 0.8)"
      } else if (state == 2) {
        return "rgba(106, 202, 106, 0.8)"
      } else if (state !== 2) {
        return "rgba(239, 239, 239, 1)"
      }
    },
    getImage(type) {
      switch (type) {
        case 1:
          return "https://pic.kanglailab.com/common/beeper.png";
        case 3:
          return "https://pic.kanglailab.com/common/smoke.png";
        case 4:
          return "https://pic.kanglailab.com/common/gas.png";
        case 5:
          return "https://pic.kanglailab.com/common/doorLock.png";
        case 6:
          return "https://pic.kanglailab.com/common/waterFlood.png";
        // case 7:
        //   return "https://pic.kanglailab.com/common/gas.png"
        case 8:
          return "https://pic.kanglailab.com/common/sos.png";
        case 9:
          return "https://pic.kanglailab.com/common/radar.png";
        case 10:
          return "https://pic.kanglailab.com/common/infrared.png";
        case 11:
          return "https://pic.kanglailab.com/common/sleep.png";
        case 12:
          return "https://pic.kanglailab.com/common/sugar.png";
        case 13:
          return "https://pic.kanglailab.com/common/pressure.png";
        case 14:
          return "http://pic.kanglailab.com/common/dynamic-pressure.png";
        case 15:
          return "http://pic.kanglailab.com/common/crutch.png";
        case 16:
          return "http://pic.kanglailab.com/common/badge.png";
        case 17:
          return "http://pic.kanglailab.com/common/watch.png";
      }
    },
    async getVillageList() {
      const { streetIds } = this.filters;
      const params = {
        provinceId: streetIds[0] || "",
        cityId: streetIds[1] || "",
        areaId: streetIds[2] || "",
        streetId: streetIds[3] || ""
      };
      const { data } = await VillageAPi.villageList(params);
      this.villageList = data || [];
    },
    async getResidentAddressList() {
      const { data } = await VillageAreaApi.getListTree({
        villageId: this.filters.villageId
      });
      this.residentAddressList = data || [];
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listData();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listData();
    },
    handleClickDetail(item) {
      this.$router.push({
        path: "/resident/residentCardDetail",
        query: {
          userId: item.userId,
          localeIds: item.strLocaleIds
        }
      });
    },
    handleEquipDetail({ type, code }) {
      let name = "";
      switch (type) {
        case 1:
          name = "BeeperManagement";
          break;
        case 3:
          name = "SmokeManagement";
          break;
        case 4:
          name = "GasManagement";
          break;
        case 5:
          name = "DoorLockManagement";
        case 6:
          name = "WaterFloodManagement";
          break;
        case 8:
          name = "SosManagement";
          break;
        case 9:
          name = "RadarManagement";
          break;
        case 10:
          name = "InfraredManagement";
        case 11:
          name = "SleepManagement";
        case 12:
          name = "SugarManagement";
        case 13:
          name = "PressureManagement";
        case 14:
          name = "DynamicPressureManagement";
        case 15:
          name = "CrutchManagement";
        case 16:
          name = "BadgeManagement";
        case 17:
          name = "WatchManagement";

      }
      this.$router.push({
        name,
        params: {
          equipCode: code
        }
      });
    },
    handleItemChange(val) {
      this.filters.provinceId = val.provinceId;
      this.filters.cityId = val.cityId;
      this.filters.areaId = val.areaId;
      this.filters.streetId = val.streetId;
      if (val.provinceId) {
        this.filters.streetIds = [
          val.provinceId,
          val.cityId,
          val.areaId,
          val.streetId
        ];
      } else {
        this.filters.streetIds = [];
      }
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch()
    },
    listData(isAdd) {
      let params = {
        name: this.filters.name,
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        provinceId: this.filters.provinceId,
        cityId: this.filters.cityId,
        areaId: this.filters.areaId,
        streetId: this.filters.streetId,
        address: this.filters.address,
        villageName: this.filters.villageName,
        floorId: this.filters.residentAddress[2] || "",
        unitId: this.filters.residentAddress[1] || "",
        buildId: this.filters.residentAddress[0] || ""
      };
      this.loading = true;
      ResidentCardApi.listResidentCard(params)
        .then(res => {
          this.page.pageTotal = res.data.total;
          this.page.totalPage = res.data.totalPage;
          this.dataList = res.data.list;
          this.dataList.forEach(item => {
            let arr = [];
            if (item.equipList && item.equipList.length > 0) {
              item.equipList.forEach(item => {
                const last = arr.at(-1);
                if (last && last.length < 4) {
                  last.push(item);
                } else {
                  arr.push([item]);
                }
              });
              item.equipList = arr;
            }else{
              item.equipList = []
            }

            // item.equipList
          });
          // if (isAdd) {
          //   this.dataList = this.dataList.concat(res.data.list);
          // } else {
          //   this.dataList = res.data.list;
          // }
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/views/content.scss";
</style>
<style lang="scss" scoped>
.opration_wrap {
  align-items: center;

  .el-tabs {
    &::v-deep .el-tabs__header {
      margin-bottom: 5px;

      .el-tabs__nav-wrap {
        &::after {
          display: none;
        }
      }
    }
  }

  .refrush {
    width: 30px;
    height: 30px;
  }
}

.table-wrapper {
  border: 1px solid #e6e6e6;
  display: grid;
  display: -ms-grid;
  justify-content: space-between;
  align-content: start;
  grid-template-columns: repeat(auto-fill, 440px);
  -ms-grid-columns: repeat(auto-fill, 440px);
  grid-gap: 10px;
  padding: 10px 8px;
  overflow: auto;

  .list-item {
    // width: 300px;
    box-shadow: 0 0 10px rgba(231, 232, 222, 1);
    border-radius: 8px;
    box-sizing: border-box;
    padding: 10px;

    .list-item__header {
      display: flex;
      position: relative;
      padding-bottom: 10px;
      border-bottom: 1px solid #f4f4f4;

      .num {
        position: absolute;
        // background-color: #F56C6C;
        background-image: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%);
        width: 100px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        font-size: 16px;
        font-weight: bold;
        color: white;
        top: 10px;
        right: -10px;
        border-top-left-radius: 20px;
        border-bottom-left-radius: 20px;
      }

      .base-info {
        margin-left: 20px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding: 5px 0;
        color: #434344;

        .name {
          font-size: 25px;
          font-weight: bold;
        }

        .sex {
          font-size: 15px;

          img {
            margin-left: 4px;
            vertical-align: -1px;
          }
        }

        .age {
          font-size: 16px;
        }
      }
    }

    .list-item__middle {
      margin-top: 5px;

      &>div {
        margin-top: 4px;
        line-height: 20px;
        display: flex;
        color: #434344;

        .label {
          color: #434344;
          width: 62px;
        }

        .value {
          height: 40px;
          flex: 1;
          display: -webkit-box;
          overflow: hidden;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          text-overflow: ellipsis;
        }
      }
    }

    .list-item__equip {
      margin-top: 10px;

      .equip-list {
        display: flex;
        flex-wrap: nowrap;

        .equip-item__wrapper {
          flex-shrink: 0;
          width: 33.3%;

          .equip-item {
            text-align: center;
            margin: 3px;
            border-radius: 5px;
            color: #909399;
            line-height: 20px;

            .equip-name {
              // line-height: 25px;
            }

            .equip-other {
              padding-bottom: 3px;
              color: #909399;
              // text-align: start;
            }
          }
        }
      }
    }
  }

  .empty {
    text-align: center;
    margin: 40px auto;
    color: #909399;
    font-size: 14px;
    align-self: center;
    grid-column: 1 / -1;
    -ms-grid-column: 1 / -1;
  }
}
</style>
